package com.cy.goods.dao;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {
    @Autowired
    private DataSource dataSource;
    @Override
    public List<Map<String,Object>> findGoods() throws SQLException {
        Connection conn=null;//java.sql.*
        Statement stat=null;
        ResultSet rs=null;
        String sql="select * from tb_goods";
        //1.获取连接(从连接池获取)
        try {
            conn=dataSource.getConnection();
            //2.创建statement对象
            stat=conn.createStatement();
            //3.发送sql
            rs=stat.executeQuery(sql);
            //4.处理结果
            List<Map<String,Object>> list=new ArrayList<>();
            Map<String,Object> map=new HashMap();
            while(rs.next()){//循环一次取一行,一行记录映射为一个map对象
                //将存储了一行记录的map对象再存储到list集合
                map.put("id", rs.getInt(1));
                map.put("name", rs.getString(2));
                map.put("remat", rs.getString(3));
                map.put("createdTime", rs.getTimestamp(4));
                list.add(map);
            }

            return list;
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException(e);//转换为非检查异常(编译时不检测的异常)
        }finally{
            //5. 释放资源
            rs.close();
            stat.close();
            conn.close();
        }
    }


}


